// store/modules/billSlice.js
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { createJSONStorage, devtools, persist } from 'zustand/middleware'
import axios from 'axios'

const createBillSlice = create(
  immer(
    devtools(
      persist(
        (set, get) => ({
          // 账单
          bills: []
        }),
        {
          name: 'billSlice',
          // partialize: (state) => ({
          //   bills: state.bills
          // }),
          storage: createJSONStorage(() => localStorage)
        }
      ),
      { enabled: true, name: 'Bill Store' }
    )
  )
)

export const setBills = async () => {
  const URL = 'http://localhost:3001/ddw'
  const res = await axios.get(URL)
  createBillSlice.setState((state) => {
    state.bills = res.data
  })
}

// 添加账单
export const addBill = async (bill) => {
  const URL = 'http://localhost:3001/ddw'
  const res = await axios.post(URL, bill)
  createBillSlice.setState((state) => {
    state.bills.push(res.data)
  })
}

export default createBillSlice
